<template>
  <div class="personal-container">
    <!-- 顶部导航栏 -->
    <el-header class="navbar">
      <div class="logo">思不罔学习平台</div>
      <el-menu mode="horizontal" :default-active="activeMenu" @select="handleSelect">
        <el-menu-item index="1" @click="goBackHome">首页</el-menu-item>
        <el-menu-item index="2" @click="goToPersonal">个人中心</el-menu-item>
        <el-menu-item index="3" @click="goToCollection">我的收藏</el-menu-item>
      </el-menu>
      <div class="auth-buttons">
        <span class="welcome-text">欢迎, {{ userInfo.username }}</span>
        <el-button type="text" @click="logout">退出登录</el-button>
      </div>
    </el-header>

    <!-- 主体内容 -->
    <el-main class="main-content">
      <el-row :gutter="20">
        <!-- 左侧个人信息卡片 -->
        <el-col :span="8">
          <el-card class="info-card">
            <!-- 头像和用户信息 -->
            <div class="avatar-container">
              <el-avatar :size="120" :src="userInfo.avatar" />
            </div>
            <h3 class="username">{{ userInfo.username }}</h3>
            <p class="user-title">{{ userInfo.professional || '未设置专业' }}</p>

            <!-- 学习统计 -->
            <div class="stats-container">
              <div class="stat-item">
                <span class="stat-value">{{ userInfo.studyDays || 0 }}</span>
                <span class="stat-label">学习天数</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ userInfo.completionRate || 0 }}%</span>
                <span class="stat-label">完成率</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧信息编辑区域 -->
        <el-col :span="16">
          <el-card class="edit-card">
            <div class="card-header">
              <h2>个人信息设置</h2>
              <div>
                <el-button
                    type="primary"
                    plain
                    @click="goToChangePsw"
                >
                  <el-icon class="el-icon--left"><Lock /></el-icon>
                  修改密码
                </el-button>
                <el-button
                    type="primary"
                    @click="saveUserInfo"
                    :loading="saving"
                >
                  <el-icon class="el-icon--left"><Check /></el-icon>
                  保存修改
                </el-button>
              </div>
            </div>

            <el-form
                :model="userInfo"
                :rules="rules"
                ref="userForm"
                label-width="100px"
                label-position="top"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="用户名" prop="username">
                    <el-input
                        v-model="userInfo.username"
                        placeholder="请输入用户名"
                        class="form-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="专业" prop="professional">

                    <el-select
                        v-model="userInfo.professional"
                        placeholder="请选择您的专业"
                        class="form-input"
                        filterable
                        clearable
                        style="margin-top: 14px;"
                    >
                      <el-option
                          v-for="major in majorList"
                          :key="major"
                          :label="major"
                          :value="major"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="电子邮箱" prop="email">
                    <el-input
                        v-model="userInfo.email"
                        placeholder="请输入电子邮箱"
                        class="form-input"
                    />
                  </el-form-item>
                </el-col>
                <!-- 添加一个空列保持布局平衡 -->
                <el-col :span="12"></el-col>
              </el-row>
            </el-form>
          </el-card>

          <!-- 学习记录卡片 -->
          <el-card class="history-card">
            <h3>最近学习记录</h3>
            <el-timeline>
              <el-timeline-item
                  v-for="(record, index) in studyHistory"
                  :key="index"
                  :timestamp="record.time"
                  placement="top"
              >
                <el-card>
                  <h4>{{ record.title }}</h4>
                  <p>{{ record.description }}</p>
                  <div class="record-meta">
                    <span>用时: {{ record.duration }}</span>
                    <span>得分: {{ record.score }}</span>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Check } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from "@/api/server"
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/useUserstore'

const router = useRouter()
const userStore = useUserStore()
const userForm = ref(null)

// 顶部导航栏激活状态
const activeMenu = ref('2')

// 用户信息
const userInfo = reactive({
  userId: '',
  username: '',
  email: '',
  professional: '',
  avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  studyDays: 0,
  completionRate: 0
})

// 专业列表
const majorList = ref([])

// 学习历史记录
const studyHistory = ref([
  {
    time: '2023-10-15 14:30',
    title: '顺序练习题',
    description: '完成了20道顺序练习题',
    duration: '32分钟',
    score: '85分'
  },
  {
    time: '2023-10-14 09:15',
    title: '随机练习题',
    description: '完成了15道随机练习题',
    duration: '25分钟',
    score: '90分'
  },
  {
    time: '2023-10-12 19:40',
    title: '题型专项练习',
    description: '完成了选择题专项训练',
    duration: '45分钟',
    score: '78分'
  }
])

// 表单验证规则
const rules = reactive({
  username: [
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: ['blur', 'change'] }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  professional: [
    { max: 50, message: '专业名称不能超过50个字符', trigger: 'blur' }
  ]
})

// 保存状态
const saving = ref(false)

// 获取专业列表的方法
const fetchMajorList = async () => {
  try {
    const response = await axios.get('/admin/manage/majors')
    if (response.data.code === 1 && response.data.data) {
      // 提取专业名称
      majorList.value = response.data.data.map(item => item.majorName)
    } else {
      ElMessage.error('获取专业列表失败：' + (response.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取专业列表失败', error)
    ElMessage.error('获取专业列表失败，请稍后重试')
  }
}

// 菜单选择处理
const handleSelect = (index) => {
  console.log('当前菜单项：', index)
}

// 导航方法
const goToChangePsw=()=>router.push('/changepsw')
const goBackHome = () => router.push('/home')
const goToPersonal = () => router.push('/personal')
const goToCollection = () => router.push('/collection')
const logout = async () => {
  try {
    await axios.post('/users/logout'); // 会自动带上 Bearer token
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    ElMessage.success('退出成功');
    await router.push('/');
  } catch (error) {
    console.error('退出失败：', error);
    ElMessage.error('退出失败');
  }
};

const saveUserInfo = async () => {
  saving.value = true

  try {
    // 获取store中的原始用户信息
    const originalValues = userStore.userInfo
    // 检查哪些字段被修改了
    const modifiedFields = {}

    if (userInfo.username !== originalValues.username) {
      modifiedFields.username = userInfo.username
    }
    if (userInfo.email !== originalValues.email) {
      modifiedFields.email = userInfo.email
    }
    if (userInfo.professional !== originalValues.professional) {
      modifiedFields.professional = userInfo.professional
    }

    // 如果没有修改任何内容
    if (Object.keys(modifiedFields).length === 0) {
      ElMessage.warning('没有检测到任何修改')
      saving.value = false
      return
    }

    // 验证修改过的字段
    const validationTasks = []

    if (modifiedFields.username) {
      validationTasks.push(
          new Promise((resolve, reject) => {
            if (modifiedFields.username.length < 3 || modifiedFields.username.length > 20) {
              reject(new Error('用户名长度需在3-20个字符之间'))
            } else {
              resolve()
            }
          })
      )
    }

    if (modifiedFields.email) {
      validationTasks.push(
          new Promise((resolve, reject) => {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
            if (!emailRegex.test(modifiedFields.email)) {
              reject(new Error('请输入有效的邮箱地址'))
            } else {
              resolve()
            }
          })
      )
    }

    // 等待所有验证完成
    await Promise.all(validationTasks)

    // 准备发送的数据
    const userData = {
      userId: userInfo.userId,
      ...modifiedFields
    }

    // 调用后端接口保存用户信息
    const response = await axios.put('/users/modifyinfo', userData)

    if (response.data.code === 1) {
      ElMessage.success('个人信息更新成功')

      // 更新store中的用户信息
      userStore.setUserInfo({
        ...userStore.userInfo,
        ...modifiedFields
      })
    } else {
      ElMessage.error('保存失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('保存用户信息失败', error)
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('保存失败，请稍后重试')
    }
  } finally {
    saving.value = false
  }
}

// 组件挂载时加载用户信息
onMounted(async () => {
  await fetchMajorList()

  // 从store获取用户ID
  const storedUser = userStore.userInfo || JSON.parse(localStorage.getItem('userInfo') || '{}')

  if (!storedUser.userId) {
    ElMessage.error('用户信息获取失败，请重新登录')
    goToLogin()
    return
  }

  try {
    // 修改为新的接口调用方式
    const response = await axios.get('/users')  // 这里修改为新的接口路径

    if (response.data.code === 1 && response.data.data) {
      const userData = response.data.data

      // 填充用户信息
      Object.assign(userInfo, {
        userId: userData.userId,
        username: userData.username,
        email: userData.email,
        professional: userData.professional,
        avatar: userData.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      })

      // 更新store中的用户信息
      userStore.setUserInfo({
        ...userStore.userInfo,
        ...userData
      })
    } else {
      ElMessage.error('获取用户信息失败：' + (response.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    ElMessage.error('获取用户信息失败，请稍后重试')
  }

  // 模拟从后端获取学习统计数据
  setTimeout(() => {
    userInfo.studyDays = 16
    userInfo.completionRate = 76
  }, 800)
})

</script>
<style scoped>
@import "../styles/Home.css";
/* 主体内容样式优化 */
.personal-container {
  background-color: var(--bg);
  min-height: 100vh;
}

.main-content {
  padding: 30px 40px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 卡片通用样式 */
.el-card {
  border-radius: 12px !important;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08) !important;
  border: none !important;
  margin-bottom: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12) !important;
}

/* 个人信息卡片 */
.info-card {
  text-align: center;
  padding: 30px 20px;
  height: 40%;
}

.avatar-container {
  margin: 0 auto 20px;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 4px solid #e9ecef;
  overflow: hidden;
}

.username {
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 5px;
  color: var(--text);
}

.user-title {
  color: var(--text-light);
  margin-bottom: 25px;
  font-size: 15px;
}

.stats-container {
  display: flex;
  justify-content: space-around;
  margin-top: 25px;
}

.stat-item {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--primary);
}

.stat-label {
  font-size: 13px;
  color: var(--text-light);
  margin-top: 5px;
}

/* 编辑卡片 */
.edit-card {
  padding: 25px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.card-header h2 {
  font-size: 22px;
  color: var(--text);
  font-weight: 600;
}

.form-input {
  width: 100%;
}

/* 学习记录卡片 */
.history-card {
  padding: 25px;
}

.history-card h3 {
  font-size: 20px;
  margin-bottom: 25px;
  color: var(--text);
  font-weight: 600;
}

.record-meta {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  color: var(--text-light);
  font-size: 13px;
}

/* 时间线样式优化 */
.el-timeline-item__wrapper {
  padding-left: 20px;
}

.el-timeline-item__timestamp {
  color: var(--text-light);
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .el-col {
    width: 100%;
  }

  .navbar {
    padding: 0 20px;
  }

  .main-content {
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .card-header h2 {
    font-size: 20px;
  }
}
</style>
